<template>
  <view class="choose-house-card">
    <view class="choose-house-header">
      <text class="choose-house-title">2、关联房屋</text>
    </view>
    
    <view v-if="houseOptions.length > 0">
      <!-- 漏选房屋提示 -->
      <view class="choose-house-add-btn" @click="handleChooseHouse()">
        <text class="choose-house-add-text">漏选房屋？</text>
        <text class="choose-house-add-link">去添加</text>
        <u-icon name="arrow-right" size="16" color="#3C75FA"></u-icon>
      </view>
      
      <!-- 房屋列表 -->
      <view class="house-list">
        <view 
          v-for="house in displayedHouses" 
          :key="house.id" 
          :class="['house-item', { 'new-house': house.isNew }, { 'voted-house': house.hasVoted }]"
        >
          <view class="house-item-left">
            <text class="house-text">{{ house.label }}</text>
            <text class="house-area">({{ house.area }}m²)</text>
          </view>
          <view v-if="house.isNew" class="new-tag">新增</view>
          <view v-if="house.hasVoted" class="voted-tag">已投票</view>
        </view>
      </view>
      
      <!-- 展开/收起按钮 -->
      <view v-if="showExpandBtn" class="expand-btn" @click="isExpanded = !isExpanded">
        <text class="expand-text">{{ isExpanded ? '收起' : '展开' }}</text>
        <u-icon :name="isExpanded ? 'arrow-up' : 'arrow-down'" size="16" color="#3C75FA"></u-icon>
      </view>
      
      <!-- 统计信息 -->
      <view class="house-summary">
        <text class="summary-text">
          共计票权{{ totalVotes }}票，专有部分面积累计{{ totalArea }}m²</text>
      </view>
      
      <!-- 面积有误提示 -->
      <view class="choose-house-warning">
        <u-image :src="warning" width="28" height="28"></u-image>
        <text class="choose-house-warning-text">若面积有误，请联系投票组织方进行变更。</text>
      </view>
    </view>
    
    <view v-else>
      <view class="choose-house-btn" @click="handleChooseHouse()">
        <view class="choose-house-btn-plus">
            <u-icon name="plus" size="15" color="#3C75FA" ></u-icon>
        </view>
        <text  class="choose-house-btn-text">添加</text>
      </view>
    </view>
    
    <u-picker  :immediateChange="true"  keyName="label"
     :show="show" :columns="[houseOptions]" @cancel="handleCancel" 
       @confirm="onPickerConfirm"></u-picker>
  
  </view>
</template>

<script>
import warning from '@/static/warning.svg'
export default {
  name: 'ChooseAHouse',
  props:{
    houseList:{
      deep:true,
      immediate:true,
      type:Array,
      default:()=>[]
    },
    isVotingInfo:{
      deep:true,
      immediate:true,
      type:Object,
      default:()=>{}
    },
    voteId:{
      type:[String, Number],
      default:''
    },
    communityId:{
      type:[String, Number],
      default:''
    },
    isRevote:{
      type:Boolean,
      default:false
    },
    votedHouseIds:{
      type:Array,
      default:()=>[]
    },
    houseCheckResult:{
      type:Object,
      default:()=>({
        successHouse: [],
        failedHouse: []
      })
    },
    isFromRelatedHouses:{
      type:Boolean,
      default:false
    },
    mobile:{
      type:String,
      default:''
    },
    initiator:{
      type:String,
      default:''
    }
  },
  watch:{
    isVotingInfo:{
      handler(newVal){
       this.isChecked()
      },
      deep:true,
      immediate:true
    }
  },
  data() {
    return {
      
      isActive:false,
      warning,
      show: false, // 控制u-picker显示
      selectedHouse: null,
      isExpanded: false // 控制房屋列表展开/收起
    }
  },
  computed: {
    houseOptions() {
      console.log('ChooseAHouse Props检查:', {
        isRevote: this.isRevote,
        votedHouseIdsLength: this.votedHouseIds?.length,
        houseListLength: this.houseList?.length,
        houseCheckResult: this.houseCheckResult
      })
      
      // 适配u-picker的数据格式，label为显示内容
      let rows= this.houseList.map((house) => {
       console.log('house',house.houseSize)
        let text=(house.areaInfo?house.areaInfo.replace(/#/g, "-"):"")+"-"+house.roomCode
        
        // 判断是否需要使用 houseCheckResult 进行判定
        // 1. 未投票状态
        // 2. 从关联房屋页面返回
        const shouldUseCheckResult = !this.isVotingInfo.isVoting || this.isFromRelatedHouses
        
        // 检查房屋是否已投票（从 houseCheckResult 中判断）
        // failedHouse 中的房屋是已投票的
        let hasVoted = false
        if (shouldUseCheckResult && this.houseCheckResult && this.houseCheckResult.failedHouse && this.houseCheckResult.failedHouse.length > 0) {
          hasVoted = this.houseCheckResult.failedHouse.some(failedHouse => 
            String(failedHouse.pmsHouse?.houseId) === String(house.houseId)
          )
          console.log('投票状态检查:', { 
            houseId: house.houseId, 
            hasVoted,
            isVoting: this.isVotingInfo.isVoting,
            isFromRelatedHouses: this.isFromRelatedHouses
          })
        }
        
        // 判断是否为新增房屋（只有在未投票的情况下才判断是否新增）
        let isNew = false
        if (!hasVoted && this.isRevote) {
          console.log('重新投票检查:', {
            isRevote: this.isRevote,
            currentHouseId: house.houseId,
            votedHouseIds: this.votedHouseIds,
            votedHouseIdsLength: this.votedHouseIds?.length
          })
          
          if (this.votedHouseIds && this.votedHouseIds.length > 0) {
            // 如果是重新投票，检查该房屋是否在已投票房屋列表中
            const hasVotedInPrevious = this.votedHouseIds.some(votedHouse => 
              String(votedHouse.houseId) === String(house.houseId)
            )
            isNew = !hasVotedInPrevious // 不在已投票列表中则为新增
            console.log('房屋状态:', { houseId: house.houseId, hasVotedInPrevious, isNew })
          }
        }
        
        return ({
        id:house.houseId,
        label:text,
        area:house.houseSize,
        isNew:isNew,
        hasVoted:hasVoted
      })
      })
     
      console.log('最终房屋列表:', rows)
      return rows
    },
    selectedHouseLabel() {
      if (!this.selectedHouse) return ''
      return this.selectedHouse.label || this.selectedHouse.name || `${this.selectedHouse.building || ''}${this.selectedHouse.unit || ''}${this.selectedHouse.room || ''}`
    },
    // 计算总面积（只计算未投票的房屋面积）
    totalArea() {
      return this.houseOptions.reduce((sum, house) => {
        console.log('house',house.area)
        // 只累加未投票的房屋面积
        if (!house.hasVoted) {
          return sum + (parseFloat(house.area) || 0)
        }
        return sum // 已投票的房屋不累加，直接返回当前sum
      }, 0).toFixed(1)
    },
    // 计算票权数量（当前简化为房屋数量）
    totalVotes() {
      return 1
    },
    // 显示的房屋列表（展开时全部显示，收起时只显示前3个）
    displayedHouses() {
      if (this.isExpanded || this.houseOptions.length <= 3) {
        return this.houseOptions
      }
      return this.houseOptions.slice(0, 3)
    },
    // 是否显示展开/收起按钮
    showExpandBtn() {
      return this.houseOptions.length > 3
    }
  },
  methods:{
    isChecked(){

      if(this.isVotingInfo.isVoting){
         this.selectedHouse=this.houseOptions.find((item)=>item.id==this.isVotingInfo.houseId)
         this.isActive=true
      }
    },
  async  handleChooseHouse(){
    console.log("1111")
      let res=await this.$store.dispatch("community/checkLoginAndBoundHouses")
      if(!res) return
      console.log('mobile',this.mobile)
      // 将房屋列表存储到本地缓存，供关联房屋页面使用
      uni.setStorageSync('tempHouseList', this.houseList)
      
      // 跳转到关联房屋页面
      uni.navigateTo({
        url: `/pages/relatedhouses/index?voteId=${this.voteId}&communityId=${this.communityId}&mobile=${this.mobile}&initiator=${this.initiator}`
      })
    },
    handleCancel(){
      this.show=false
    },
    onPickerConfirm(e) {
   
      // e.value 是选中的项数组
      this.selectedHouse = e.value[0]
      this.isActive = true
      this.show = false
      this.$emit('confirm', this.selectedHouse)
    }
  }
}
</script>

<style scoped lang="scss">
.choose-house-card {
  background: #fff;
  border-radius: 18rpx;
  padding: 30rpx 20rpx 32rpx 25rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx 0 rgba(0,0,0,0.04);
  margin-top: 20rpx;
}
.choose-house-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}
.choose-house-title {
  font-weight: 600;
  font-size: 30rpx;
  color: #000000;
}

// 漏选房屋按钮
.choose-house-add-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 0;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  border: 2rpx solid #E8F0FF;
  border-radius: 12rpx;
  background: #F7FAFF;
}
.choose-house-add-text {
  font-size: 28rpx;
  color: #666666;
  margin-right: 8rpx;
}
.choose-house-add-link {
  font-size: 28rpx;
  color: #3C75FA;
  margin-right: 4rpx;
}

// 房屋列表
.house-list {
  margin-bottom: 0rpx;
}
.house-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 30rpx;
  margin-bottom: 16rpx;
  background: #F8F9FA;
  border-radius: 12rpx;
  border: 2rpx solid #E8E9EB;
  position: relative;
}
.house-item.new-house {
  background: #FFF8F0;
  border: 2rpx solid #FFD9B3;
  border-left: 6rpx solid #FF9933;
}
.house-item.voted-house {
  background: #F0F9F4;
  border: 2rpx solid #B3E5C5;
  border-left: 6rpx solid #52C41A;
}
.house-item-left {
  display: flex;
  align-items: center;
}
.house-text {
  font-size: 28rpx;
  color: #333333;
  margin-right: 8rpx;
}
.house-area {
  font-size: 28rpx;
  color: #666666;
}
.new-tag {
  padding: 4rpx 16rpx;
  background: #FF9933;
  color: #FFFFFF;
  font-size: 24rpx;
  border-radius: 6rpx;
  font-weight: 500;
}
.voted-tag {
  padding: 4rpx 16rpx;
  background: #52C41A;
  color: #FFFFFF;
  font-size: 24rpx;
  border-radius: 6rpx;
  font-weight: 500;
}

// 展开/收起按钮
.expand-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 0;
  margin-bottom: 24rpx;
  cursor: pointer;
}
.expand-text {
  font-size: 28rpx;
  color: #3C75FA;
  margin-right: 8rpx;
}

// 统计信息
.house-summary {
  padding: 24rpx;
  margin-bottom: 20rpx;
  background: #E8F0FF;
  border-radius: 12rpx;
}
.summary-text {
  font-size: 28rpx;
  color: #3C75FA;
  text-align: center;
  display: block;
}

.choose-house-warning {
  display: flex;
  align-items: center;
  color: #F9901B;
  font-size: 24rpx;
}
.choose-house-warning-text {
  margin-left: 8rpx;
  line-height: 1.5;
}
.choose-house-btn {
  width: 100%;
  border: 2rpx solid $uni-color-primary ;
  border-radius: 12rpx;
  color: $uni-color-primary ;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
 
  margin-top: 18rpx;
}

.choose-house-btn-text {
  font-size: 30rpx;
  font-weight: 400;
  margin-left: 12rpx;
}
</style>
